package com.nulldev.util.crypto.api2.encryptors;

import java.nio.charset.Charset;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

import com.nulldev.util.crypto.api2.Cryptable;
import com.nulldev.util.other.CharsetUtil;

public class tDES extends Cryptable{

	public tDES() {
		super("tDES");
	}

	@Override
	public String encrypt(String object, String pass) {
		return this.encrypt(object, pass, CharsetUtil.getCharset());
	}

	@Override
	public String decrypt(String object, String pass) {
		return this.decrypt(object, pass, CharsetUtil.getCharset());
	}
	
	@Override
	public String encrypt(String object, String pass, Charset charset) {
		try {
			return new String(encTripleDes(object, pass.getBytes(), charset), charset);
		} catch (Exception e) {
			e.printStackTrace();
			return object;
		}
	}

	@Override
	public String decrypt(String object, String pass, Charset charset) {
		try {
			return new String(uncTripleDes(object.getBytes(charset), pass.getBytes()), charset);
		} catch (Exception e) {
			e.printStackTrace();
			return object;
		}
	}
	
	public byte[] encTripleDes(String txt, byte[] key, final Charset charset) throws Exception {
	    DESedeKeySpec keySpec = new DESedeKeySpec(key);
	    SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
	    SecretKey ky = keyfactory.generateSecret(keySpec);

	    Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
	    cipher.init(Cipher.ENCRYPT_MODE, ky);
	    return cipher.doFinal(txt.getBytes(charset));
	}
	
	public byte[] uncTripleDes(byte [] encryptedTextBytes, byte[] key) throws Exception {
	    DESedeKeySpec keySpec = new DESedeKeySpec(key);
	    SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
	    SecretKey ky = keyfactory.generateSecret(keySpec);

	    Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
	    cipher.init(Cipher.DECRYPT_MODE, ky);
	    return cipher.doFinal(encryptedTextBytes);

	}

}
